﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using webapi.Model;

namespace webapi.Helper
{
    public class JwtHelper
    {
        IConfiguration _configuration;
        public JwtHelper(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public string GenerateJwtToken(UserJwt user)
        {
            var claims = new[]
            {
             new Claim(JwtRegisteredClaimNames.Sub, user.UserEmail),
             new Claim("UserEmail", user.UserEmail),
             // 0: 普通用户， 1：管理员....
             new Claim("UserGroupId", user.UserGroupId),
             new Claim("UserGuid", user.UserGuid),
             new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
             // 添加其他claims，如角色等
         };
            var res = Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]);
            var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
            var signingCredentials = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);

            SecurityToken jwtSecurityToken = new JwtSecurityToken(
                issuer: _configuration["Jwt:Issuer"],
                audience: _configuration["Jwt:Audience"],
                claims: claims,
                expires: DateTime.Now.AddDays(7), // Token有效期
                signingCredentials: signingCredentials
            );

            return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
        }
    }
}